package acwing.lq.递归and递推;

import java.util.Scanner;

/**
 * @description:
 * @author: qian
 * @createDate: 2021/11/17
 */
public class 费解的开关 {

    static int N = 6;
    static int[][] bg = new int[N][N];
    static int[][] g = new int[N][N];
    static int[] dx = new int[] {0,-1,0,1,0};
    static int[] dy = new int[] {-1,0,1,0,0};

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        while (n-- > 0) {
            int res = 10;
            for (int i = 0; i < 5; i++) {
                String s = scan.next();
                for(int j = 0;j < 5;j ++)
                    bg[i][j] = s.charAt(j) - '0';
            }
            for (int op = 0; op < 1 << 5; op++) {
                int cnt = 0;
                //取出备份
                for(int u = 0;u < 5;u ++)
                    for(int v = 0;v < 5;v ++)
                        g[u][v] = bg[u][v];
                for (int i = 0; i < 5; i++) {
                    if ((op >> i & 1) == 1) {
                        trun(0, i);
                        cnt++;
                    }
                }
                for (int i = 0; i < 4; i++) {
                    for (int j = 0; j < 5; j++) {
                        if (g[i][j] == 0) {
                            trun(i + 1, j);
                            cnt++;
                        }
                    }
                }
                boolean flag = true;
                for (int i = 0; i < 5; i++) {
                    if(g[4][i] == 0) {
                        flag = false;
                    }
                }
                if (flag && res > cnt) res = cnt;
            }
            if (res > 6) res = -1;
            System.out.println(res);
        }
    }

    private static void trun(int x, int y) {
        for (int i = 0; i < 5; i++) {
            int a = x + dx[i];
            int b = y + dy[i];
            if (a < 0 || a >= 5 || b < 0 || b >= 5) continue;
            g[a][b] ^= 1;
        }

    }
}
